package com.zhongshengnetwork.rightbe.wzt.activity;

//import android.support.v7.app.AppCompatActivity;
import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
//import android.support.annotation.NonNull;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.FileProvider;
//import android.support.v7.widget.RecyclerView;
//import android.support.v7.widget.StaggeredGridLayoutManager;
//import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.hys.utils.AppUtils;
import com.hys.utils.ImageUtils;
import com.hys.utils.InitCacheFileUtils;
import com.hys.utils.SdcardUtils;
import com.wang.avi.AVLoadingIndicatorView;
import com.yalantis.ucrop.UCrop;
import com.zhongshengnetwork.rightbe.BuildConfig;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ImageCompressUtils;
import com.zhongshengnetwork.rightbe.common.JsonMap;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.QiniuCallBack;
import com.zhongshengnetwork.rightbe.common.QiniuUploadModel;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.LangPublishdbModel;
import com.zhongshengnetwork.rightbe.dbservice.LangPublishService;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.QiniuModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuContentDetailModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuInfoDetailModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.imageviewer.ViewData;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.PublicTypeActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SearchLocationActivity;
import com.zhongshengnetwork.rightbe.lang.activity.SelfImagePreviewActivity;
import com.zhongshengnetwork.rightbe.lang.view.MyCallBack;
import com.zhongshengnetwork.rightbe.lang.view.OnRecyclerItemClickListener;
import com.zhongshengnetwork.rightbe.lang.view.PostArticleImgAdapter;
import com.zhongshengnetwork.rightbe.login.BDThirdActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.io.File;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

import static com.huantansheng.easyphotos.constant.Code.REQUEST_PERMISSION;

public class WZTContentPublishActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    public static final String FILE_DIR_NAME = "com.zhongshengnetwork.rightbe";//应用缓存地址
    public static final String FILE_IMG_NAME = "images";//放置图片缓存
    public static final int IMAGE_SIZE = 9;//可添加图片最大数
    private static final int REQUEST_PUBLISH = 1002;
    private static final int REQUEST_LOCATION = 1211;//地理位置
    private static final int TAKE_PICTURE = 1212;//拍照
    private static final int SELECT_PICTURE = 1214;//从相册选择
    private static final int REQUEST_LABEL = 1213; //选择标签
    private static final int PHOTO_PICKER_REQUEST_CODE = 10004; //android 13从相册选择一张图片
    private static final int PHOTO_PICKER_MULTI_SELECT_REQUEST_CODE = 10005; //android 13从相册选择多张图片

    private static String imageFileName = "";//拍照图片名称
    public boolean isDealWithImg = false;//是否正在处理图片
    private String imgString = "";

    private TopBarView topbar;

    private ArrayList<String> originImages;//原始图片
    private ArrayList<String> dragImages;//压缩长宽后图片
    private Context mContext;
    private PostArticleImgAdapter postArticleImgAdapter;
    private ItemTouchHelper itemTouchHelper;
    private RecyclerView rcvImg;
    private TextView tv;//删除区域提示
    private EditText et_content;

    private int imgIndex = 0;
    private QiniuModel qiniuModel = null;
    private boolean isUploading = false;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private Handler mHandler = null;
    private static int delay = 100;
    private static int period = 500;  //1s
    private boolean timerFlag = false;
    public AVLoadingIndicatorView avi;
    private boolean isRepublish = false;

    private RelativeLayout publish_menu_original;
    private LinearLayout publish_menu_original_line;
    private TextView publish_menu_original_title;
    private ImageView publish_menu_original_select;

    private RelativeLayout publish_menu_type;
    private TextView publish_menu_type_text;

    //图片浏览
    public ImageViewer imagePreivew;
    private int imgW = 0;
    List<ViewData> mViewDatas = new ArrayList<ViewData>();
    List<Object> mImageList = new ArrayList<Object>();

    private List<String> nameList = null;
    private List<String> itemList = null;
    private boolean isPublishing = false;//发布状态，控制重复发布
    private WeiShuContentDetailModel weiShuContentDetailModel;

    //绑定手机号
    private boolean bindMobile(){
        if (CommonUtils.isLogin() == true){
            if (!CommonUtils.isEmpty(CustomApplication.loginModel.getNeed()) && CustomApplication.loginModel.getNeed().equals("1")){
                if (CommonUtils.isEmpty(CustomApplication.loginModel.getMobile())){
                    Intent intent = new Intent(WZTContentPublishActivity.this, BDThirdActivity.class);
                    startActivity(intent);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wztcontent_publish);
        weiShuContentDetailModel =  (WeiShuContentDetailModel) getIntent().getSerializableExtra("model");
        if (weiShuContentDetailModel == null){
            isRepublish = false;
            weiShuContentDetailModel = new WeiShuContentDetailModel();
            String id  = getIntent().getLongExtra("id",0)+"";
            weiShuContentDetailModel.setContentType(getIntent().getByteExtra("contentType",Byte.valueOf("0")));
            weiShuContentDetailModel.setWeishuId(Integer.valueOf(id));
            weiShuContentDetailModel.setOriginal(false);
            weiShuContentDetailModel.setLongtitude(0.0f);
            weiShuContentDetailModel.setLatitude(0.0f);
        }else {
            isRepublish = true;
        }
        imgString = "";
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getRightTextView().setText("发布");
        topbar.getRightTextView().setTextSize(15);
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                if (CommonUtils.isLogin() == false){
                    Intent intent = new Intent(WZTContentPublishActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                publishLang();
            }
        });
        if (weiShuContentDetailModel.getContentType() == 2){
            topbar.getTitleView().setText("写日记");
        }
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);

        publish_menu_original = (RelativeLayout) findViewById(R.id.publish_menu_original);
        publish_menu_original_line = (LinearLayout) findViewById(R.id.publish_menu_original_line);
        publish_menu_original_title = (TextView) findViewById(R.id.publish_menu_original_title);
        publish_menu_original_select = (ImageView) findViewById(R.id.publish_menu_original_select);

        publish_menu_type = (RelativeLayout) findViewById(R.id.publish_menu_type);
        publish_menu_type_text = (TextView) findViewById(R.id.publish_menu_type_text);
        publish_menu_type.setClickable(true);
        publish_menu_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PermissionUtils.isLocationNote(WZTContentPublishActivity.this, new PermissionCallback() {
                    @Override
                    public void onResult(boolean flag, boolean showAlert) {
                        if (flag == true){
                            Intent intent = new Intent(WZTContentPublishActivity.this,SearchLocationActivity.class);
                            startActivityForResult(intent, REQUEST_LOCATION);
                        }
                    }
                });

            }
        });

        imagePreivew = (ImageViewer) findViewById(R.id.imagePreivew);
        initView();
        initData();
        initRcv();

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg == null){
                    return;
                }
                switch (msg.what) {
                    case 1:
                        if (isUploading == true){
                            break;
                        }
                        isUploading = true;
                        Bitmap bitmap = null;
                        for (; imgIndex < dragImages.size(); imgIndex++){
                            if (dragImages.get(imgIndex).contains("http")==false){
                                bitmap = ImageUtils.getBitmap(dragImages.get(imgIndex));
                                System.out.print(imgIndex+"有图片\n");
                                imgIndex++;
                                break;
                            }else {
                                if (imgString.length() >0){
                                    imgString += ",";
                                }
                                imgString += dragImages.get(imgIndex);
                            }
                        }
                        if (bitmap == null){
                            System.out.print("开始发布\n");
                            stopTimer();
                            uploadLang();
                            isUploading = false;
                        }else {
                            System.out.print("开始上传图片\n");
                            uploadImg(bitmap,imgIndex-1);
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacksAndMessages(null);
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        back();
    }

    @Override
    public void onBackPressed()
    {
        Log.e("TAG","按下返回键了");
        back();
    }

    private void back(){
        hintKeyBoard();
        final CustomDialog.Builder builder = new CustomDialog.Builder(WZTContentPublishActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("是否要放弃本次发布？");
        builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteTempFile();
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        CustomDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void initData() {

        if (isRepublish == true){
            et_content.setText(weiShuContentDetailModel.getTitle());

            if (weiShuContentDetailModel.getOriginal() == true){
                publish_menu_original_select.setImageResource(R.drawable.ios7_switch_on);
            }else {
                publish_menu_original_select.setImageResource(R.drawable.ios7_switch_off);
            }

        }
        if (originImages == null){
            originImages = new ArrayList<String>();
        }
        originImages.clear();
        if (!CommonUtils.isEmpty(weiShuContentDetailModel.getImg())){
            originImages.addAll(CommonUtils.stringToArrayList(weiShuContentDetailModel.getImg()));
        }
        mContext = getApplicationContext();
        if (PermissionUtils.hasSDCard() == true){
            InitCacheFileUtils.initImgDir(FILE_DIR_NAME, FILE_IMG_NAME);//清除图片缓存
        }
        //添加按钮图片资源
        String plusPath = getString(R.string.glide_plus_icon_string) + AppUtils.getPackageInfo(mContext).packageName + "/mipmap/" + R.mipmap.bg_add_imgshow;
        dragImages = new ArrayList<>();
        originImages.add(plusPath);//添加按键，超过9张时在adapter中隐藏
        dragImages.addAll(originImages);
        new Thread(new MyRunnable(dragImages, originImages, dragImages, myHandler, false)).start();//开启线程，在新线程中去压缩图片

        publish_menu_original_line.setVisibility(View.VISIBLE);
        publish_menu_original.setVisibility(View.VISIBLE);
        publish_menu_original.setClickable(true);
        publish_menu_original.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (weiShuContentDetailModel.getOriginal() == true){
                    weiShuContentDetailModel.setOriginal(false);
                    publish_menu_original_select.setImageResource(R.drawable.ios7_switch_off);
                }else {
                    weiShuContentDetailModel.setOriginal(true);
                    publish_menu_original_select.setImageResource(R.drawable.ios7_switch_on);
                }
            }
        });

        if (!CommonUtils.isEmpty(weiShuContentDetailModel.getLocation())){
            publish_menu_type_text.setText(weiShuContentDetailModel.getLocation());
        }

    }

    private void initView() {
        rcvImg = (RecyclerView) findViewById(R.id.rcv_img);
        tv = (TextView) findViewById(R.id.tv);
        et_content = (EditText) findViewById(R.id.et_content);
        if (weiShuContentDetailModel.getContentType() == 2){
            et_content.setHint("请输入日记内容...");
        }
        RelativeLayout wztcontent_publish = (RelativeLayout) findViewById(R.id.wztcontent_publish);
        wztcontent_publish.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        et_content.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        et_content.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        publish_menu_original_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        publish_menu_original_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        LinearLayout line1 = (LinearLayout) findViewById(R.id.line1);
        line1.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        TextView publish_menu_type_title = (TextView) findViewById(R.id.publish_menu_type_title);
        publish_menu_type_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        publish_menu_type_text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        LinearLayout line2 = (LinearLayout) findViewById(R.id.line2);
        line2.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        TextView publish_tip = (TextView) findViewById(R.id.publish_tip);
        publish_tip.setTextColor(AppThemeUtils.getInstance().getLightTextColor());
    }

    private void initRcv() {

        postArticleImgAdapter = new PostArticleImgAdapter(mContext, dragImages);
        rcvImg.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
        rcvImg.setAdapter(postArticleImgAdapter);

        MyCallBack myCallBack = new MyCallBack(postArticleImgAdapter, dragImages, originImages);
        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(rcvImg);//绑定RecyclerView

        //事件监听
        rcvImg.addOnItemTouchListener(new OnRecyclerItemClickListener(rcvImg) {

            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                if (originImages.get(vh.getAdapterPosition()).contains(getString(R.string.glide_plus_icon_string))) {//打开相册

                    if (isPublishing == true){
                        ToastUtil.show(WZTContentPublishActivity.this, "正在发布...");
                        return;
                    }
                    if (isDealWithImg == true){
                        ToastUtil.show(WZTContentPublishActivity.this, "正在处理图片，请稍后...");
                        return;
                    }
                    List<String> itemList = new ArrayList<String>();
                    itemList.add("拍一张");
                    itemList.add("从相册选择");
                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(WZTContentPublishActivity.this)
                            .builder()
                            .setTitle("请选择")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String s : itemList){
                        actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which > 0){
                                    if (which == 1){
                                        doTakePhoto();
                                    }else if (which == 2){
                                        selectFromPhonePicture();
                                    }
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();

                } else {
                    onClickImageView(vh.itemView, vh.getAdapterPosition());
                    //ToastUtils.getInstance().show(CustomApplication.customApplication, "预览图片");
                }
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                //如果item不是最后一个，则执行拖拽
                if (vh.getLayoutPosition() != dragImages.size() - 1) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        });

        myCallBack.setDragListener(new MyCallBack.DragListener() {
            @Override
            public void deleteState(boolean delete) {
                if (delete) {
                    tv.setBackgroundResource(R.color.holo_red_dark);
                    tv.setText(getResources().getString(R.string.post_delete_tv_s));
                } else {
                    tv.setText(getResources().getString(R.string.post_delete_tv_d));
                    tv.setBackgroundResource(R.color.holo_red_light);
                }
            }

            @Override
            public void dragState(boolean start) {
                if (start) {
                    tv.setVisibility(View.VISIBLE);
                } else {
                    tv.setVisibility(View.GONE);
                }
            }

            @Override
            public void clearView() {

            }
        });
    }

    //从手机相册选择
    private void selectFromPhonePicture(){
        PermissionUtils.isPictureNote(WZTContentPublishActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                        if (ContextCompat.checkSelfPermission(WZTContentPublishActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(WZTContentPublishActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                    MainActivity.REQUEST_PERMISSION);
                            return;
                        }
                    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                            && ContextCompat.checkSelfPermission(WZTContentPublishActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(WZTContentPublishActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                REQUEST_PERMISSION);
                        //ToastUtil.show(WZTContentPublishActivity.this,"亲，请开启应用对SD卡的读写权限");
                        return;
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                        final int maxNumPhotosAndVideos = IMAGE_SIZE - originImages.size() + 1;
                        Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                        intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, maxNumPhotosAndVideos);
                        startActivityForResult(intent, PHOTO_PICKER_MULTI_SELECT_REQUEST_CODE);
                        return;
                    }
                    MultiImageSelector.create()
                            .showCamera(false)
                            .count(IMAGE_SIZE - originImages.size() + 1)
                            .multi()
                            .start(WZTContentPublishActivity.this, REQUEST_PUBLISH);
                }
            }
        });
    }

    /**拍照获取相片**/
    private void doTakePhoto() {
        PermissionUtils.showCamaraNote(WZTContentPublishActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (PermissionUtils.cameraIsCanUse() == true){
                        imageFileName = System.currentTimeMillis() + Constant.weijuTakePhoto;
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),imageFileName));//Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
                        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //直接使用，没有缩小
                        startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
                    }else {
                        ActivityCompat.requestPermissions(WZTContentPublishActivity.this,
                                new String[]{Manifest.permission.CAMERA},
                                1);
                    }
                }
            }
        });

    }


    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    "com.zhongshengnetwork.rightbe.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            PermissionUtils.isPictureNote(WZTContentPublishActivity.this, new PermissionCallback() {
                @Override
                public void onResult(boolean flag, boolean showAlert) {
                    if (flag == true){
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                            if (ContextCompat.checkSelfPermission(WZTContentPublishActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                                ActivityCompat.requestPermissions(WZTContentPublishActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                        MainActivity.REQUEST_PERMISSION);
                                return;
                            }
                        }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                                && ContextCompat.checkSelfPermission(WZTContentPublishActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(WZTContentPublishActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    REQUEST_PERMISSION);
                            //ToastUtil.show(WZTContentPublishActivity.this,"亲，请开启应用对SD卡的读写权限");
                            return;
                        }
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                            final int maxNumPhotosAndVideos = IMAGE_SIZE - originImages.size() + 1;
                            Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                            intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, maxNumPhotosAndVideos);
                            startActivityForResult(intent, PHOTO_PICKER_MULTI_SELECT_REQUEST_CODE);
                            return;
                        }
                        // 权限被用户同意，可以做你要做的事情了。
                        MultiImageSelector.create()
                                .showCamera(false)
                                .count(IMAGE_SIZE - originImages.size() + 1)
                                .multi()
                                .start(WZTContentPublishActivity.this, REQUEST_PUBLISH);
                    }
                }
            });
        } else {
            // 权限被用户拒绝了，可以提示用户,关闭界面等等。
            CustomDialog dialog = null;
            final CustomDialog.Builder builder = new CustomDialog.Builder(WZTContentPublishActivity.this);
            builder.setTitle("温馨提示");
            builder.setMessage("应用需要开启相机权限，是否去设置？");
            builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //跳转App设置权限的界面
                    Intent i = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
                    String pkg = "com.android.settings";
                    String cls = "com.android.settings.applications.InstalledAppDetails";
                    i.setComponent(new ComponentName(pkg, cls));
                    i.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(i);
                    finish();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog = builder.create();
            dialog.show();

        }
    }

    //------------------图片相关-----------------------------

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri imageUri = null;
        if (requestCode == REQUEST_PUBLISH && resultCode == RESULT_OK) {//从相册选择完图片
            if (data == null){
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    avi.show();
                }
            });
            isDealWithImg = true;
            //压缩图片
            new Thread(new MyRunnable(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT),
                    originImages, dragImages, myHandler, true)).start();
        }else if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK){

            /*
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    avi.show();
                }
            });
            isDealWithImg = true;
            ArrayList<String> imgList = new ArrayList<String>();
            imgList.add(imageFileName);
            new Thread(new MyRunnable(imgList,
                    originImages, dragImages, myHandler, true)).start();
            */

            try {
                Uri uri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),imageFileName));
                if (uri == null){
                    return;
                }
                float density = ScreenUtils.getScreenDensity(WZTContentPublishActivity.this);
                UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + Constant.weijuTakePhoto)))//"imageout.jpg"
                        .useSourceImageAspectRatio()
                        .withMaxResultSize((int)(1920*density), (int)(1920*density))
                        .start(WZTContentPublishActivity.this);
            }catch (Exception e){
                ToastUtil.show(WZTContentPublishActivity.this,"亲，你这次没拍好哦，再来一次哟~");
                LangPublishActivity.uploadError("微句拍照封面报错："+e.getLocalizedMessage());
            }

        }else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK){
            if (data == null){
                return;
            }
            try {
                final Uri resultUri = UCrop.getOutput(data);
                Bitmap bmap = BitmapFactory.decodeFile(resultUri.getEncodedPath());
                if (bmap != null){
                    ArrayList<String> imgList = new ArrayList<String>();
                    imgList.add(resultUri.getPath());
                    new Thread(new MyRunnable(imgList,
                            originImages, dragImages, myHandler, true)).start();

                }
            }catch (Exception e){
                ToastUtil.show(WZTContentPublishActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                LangPublishActivity.uploadError("微句裁剪封面报错："+e.getLocalizedMessage());
            }

        }else if (requestCode == REQUEST_LOCATION && resultCode == RESULT_OK){
            if (data == null){
                return;
            }
            weiShuContentDetailModel.setNation("");
            weiShuContentDetailModel.setProvince(data.getStringExtra(APIKey.provinceKey));
            weiShuContentDetailModel.setCity(data.getStringExtra(APIKey.cityKey));
            weiShuContentDetailModel.setArea("");
            weiShuContentDetailModel.setLocation(data.getStringExtra(APIKey.locationKey));
            weiShuContentDetailModel.setLongtitude(data.getDoubleExtra(APIKey.longtitudeKey,0.0f));
            weiShuContentDetailModel.setLatitude(data.getDoubleExtra(APIKey.latitudeKey,0.0f));
            publish_menu_type_text.setText(weiShuContentDetailModel.getLocation());
        }else if(requestCode == PHOTO_PICKER_MULTI_SELECT_REQUEST_CODE && resultCode == RESULT_OK){//android 13
            if (data != null){
                ArrayList<String> imgList = new ArrayList<String>();
                for (int i = 0; i < data.getClipData().getItemCount(); i++) {
                    Uri currentUri = data.getClipData().getItemAt(i).getUri();
                    imgList.add(getRealFilePath(CustomApplication.mContext, currentUri));
                    // Do stuff with each photo/video URI.
                }

                postArticleImgAdapter.filterIndex = 0;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.show();
                    }
                });
                isDealWithImg = true;
                //压缩图片
                new Thread(new MyRunnable(imgList,
                        originImages, dragImages, myHandler, true)).start();
            }
        }
    }

    public String getRealFilePath( final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 另起线程压缩图片
     */
    static class MyRunnable implements Runnable {

        ArrayList<String> images;
        ArrayList<String> originImages;
        ArrayList<String> dragImages;
        Handler handler;
        boolean add;//是否为添加图片

        public MyRunnable(ArrayList<String> images, ArrayList<String> originImages, ArrayList<String> dragImages, Handler handler, boolean add) {
            this.images = images;
            this.originImages = originImages;
            this.dragImages = dragImages;
            this.handler = handler;
            this.add = add;
        }

        @Override
        public void run() {
            SdcardUtils sdcardUtils = new SdcardUtils();
            String filePath;
            Bitmap newBitmap;
            int addIndex = originImages.size() - 1;
            for (int i = 0; i < images.size(); i++) {
                if (images.get(i).contains(CustomApplication.customApplication.getString(R.string.glide_plus_icon_string))) {//说明是添加图片按钮
                    continue;
                }
                if(images.get(i).contains("http")){
                    filePath = images.get(i);
                }else {
                    filePath = images.get(i);
                    /*
                    //压缩
                    //newBitmap = ImageUtils.compressScaleByWH(images.get(i),
                    //DensityUtils.dp2px(CustomApplication.customApplication, 100),
                    //DensityUtils.dp2px(CustomApplication.customApplication, 100));
                    Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
                    if (images.get(i).equals(imageFileName) == false){
                        format = CommonUtils.getImageType(images.get(i));
                    }
                    if (format == null){
                        continue;//不支持的图片格式
                    }
                    //文件地址
                    if (format == Bitmap.CompressFormat.JPEG){
                        filePath = sdcardUtils.getSDPATH() + FILE_DIR_NAME + "/"
                                + FILE_IMG_NAME + "/" + String.format("img_%d.jpg", System.currentTimeMillis());
                    }else if (format == Bitmap.CompressFormat.PNG){
                        filePath = sdcardUtils.getSDPATH() + FILE_DIR_NAME + "/"
                                + FILE_IMG_NAME + "/" + String.format("img_%d.png", System.currentTimeMillis());
                    }else {
                        filePath = sdcardUtils.getSDPATH() + FILE_DIR_NAME + "/"
                                + FILE_IMG_NAME + "/" + String.format("img_%d.webp", System.currentTimeMillis());
                    }
                    Log.e("TAG","图片路径："+filePath);
                    Bitmap photo = null;
                    if (images.get(i).equals(imageFileName) == false){
                        photo = ImageUtils.getBitmap(images.get(i));
                    }else {
                        photo = ImageUtils.getBitmap(new File(Environment.getExternalStorageDirectory(),imageFileName));
                    }
                    if (photo != null){
                        newBitmap = ImageCompressUtils.compressScale(photo,format);
                        if (!photo.isRecycled())
                        {
                            Log.e("TAG","图片回收：");
                            photo.recycle();
                        }
                        //保存图片
                        ImageUtils.save(newBitmap, filePath, format, true);//Bitmap.CompressFormat.JPEG
                    }else {
                        continue;//图片为空
                    }
                    */
                }
                //设置值
                if (!add) {
                    images.set(i, filePath);
                } else {//添加图片，要更新
                    dragImages.add(addIndex, filePath);
                    originImages.add(addIndex++, filePath);
                }
            }
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    }

    private MyHandler myHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private WeakReference<Activity> reference;

        public MyHandler(Activity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WZTContentPublishActivity activity = (WZTContentPublishActivity) reference.get();
            if (activity != null) {
                if (msg == null){
                    return;
                }
                switch (msg.what) {
                    case 1:
                        activity.isDealWithImg = false;
                        activity.avi.hide();
                        activity.postArticleImgAdapter.notifyDataSetChanged();
                        break;
                }
            }
        }
    }

    //以下是发布流程
    private void publishLang(){

        if (bindMobile() == true){
            return;
        }

        if(isDealWithImg == true){
            ToastUtil.show(WZTContentPublishActivity.this, "正在处理图片，请稍后...");
            return;
        }

        if (isPublishing == true){
            ToastUtil.show(WZTContentPublishActivity.this, "发布中，请稍后...");
            return;
        }

        if (et_content.getText().length() == 0){
            weiShuContentDetailModel.setTitle("");
        }else {
            weiShuContentDetailModel.setTitle(et_content.getText().toString());
        }


        if (dragImages != null && dragImages.size() > 0){
            //有图片可以没有文字
        }else {
            if (CommonUtils.isEmpty(weiShuContentDetailModel.getTitle())){
                ToastUtil.show(WZTContentPublishActivity.this, "亲，请输入微纸条内容哦~");
                return;
            }
        }
        if (CommonUtils.isEmpty(weiShuContentDetailModel.getTitle())){
            weiShuContentDetailModel.setTitle("");
        }else {
            weiShuContentDetailModel.setTitle(weiShuContentDetailModel.getTitle().replaceAll("%","﹪"));
        }

        /*
        if (CommonUtils.isEmpty(weiShuContentDetailModel.getTitle())){
            ToastUtil.show(WZTContentPublishActivity.this, "亲，请输入微纸条内容哦~");
            return;
        }
        weiShuContentDetailModel.setTitle(weiShuContentDetailModel.getTitle().replaceAll("%","﹪"));
        */


        isPublishing = true;
        if (isRepublish == true){
            /*
            avi.setVisibility(View.VISIBLE);
            avi.show();
            imgString = "";
            if (dragImages != null && dragImages.size() > 0){
                getUploadInfo();
            }else {
                uploadLang();
            }
            */
            final JsonMap<String, String> map = new JsonMap<String, String>();
            map.put("langid", weiShuContentDetailModel.getLangid());
            map.put("title",weiShuContentDetailModel.getTitle());
            map.put("weishuId",weiShuContentDetailModel.getWeishuId()+"");
            map.put("original",weiShuContentDetailModel.getOriginal()+"");

            map.put(APIKey.nationKey,CommonUtils.formatString(weiShuContentDetailModel.getNation()));
            map.put(APIKey.provinceKey,CommonUtils.formatString(weiShuContentDetailModel.getProvince()));
            map.put(APIKey.cityKey,CommonUtils.formatString(weiShuContentDetailModel.getCity()));
            map.put(APIKey.areaKey,CommonUtils.formatString(weiShuContentDetailModel.getArea()));
            map.put(APIKey.locationKey,CommonUtils.formatString(weiShuContentDetailModel.getLocation()));
            map.put(APIKey.longtitudeKey,weiShuContentDetailModel.getLongtitude()+"");
            map.put(APIKey.latitudeKey,weiShuContentDetailModel.getLatitude()+"");

            LangPublishdbModel model = new LangPublishdbModel();
            model.setData(map.toString());
            if (dragImages != null && dragImages.size() > 0){
                model.setImgdata(CommonUtils.listToString(dragImages));
            }else {
                model.setImgdata("");
            }
            model.setUserid(CustomApplication.loginModel.getUid());
            model.setDatatype(0);
            LangPublishService.saveOrUpdate(model);
            Intent intent = new Intent();
            intent.putExtra("isBacken", true);
            setResult(RESULT_OK, intent);
            //???
            finish();
        }else {
            if(CommonUtils.isEmpty(weiShuContentDetailModel.getTitle())){
                final JsonMap<String, String> imap = new JsonMap<String, String>();
                imap.put("title",weiShuContentDetailModel.getTitle());
                imap.put("weishuId",weiShuContentDetailModel.getWeishuId()+"");
                imap.put("original",weiShuContentDetailModel.getOriginal()+"");

                imap.put(APIKey.nationKey,CommonUtils.formatString(weiShuContentDetailModel.getNation()));
                imap.put(APIKey.provinceKey,CommonUtils.formatString(weiShuContentDetailModel.getProvince()));
                imap.put(APIKey.cityKey,CommonUtils.formatString(weiShuContentDetailModel.getCity()));
                imap.put(APIKey.areaKey,CommonUtils.formatString(weiShuContentDetailModel.getArea()));
                imap.put(APIKey.locationKey,CommonUtils.formatString(weiShuContentDetailModel.getLocation()));
                imap.put(APIKey.longtitudeKey,weiShuContentDetailModel.getLongtitude()+"");
                imap.put(APIKey.latitudeKey,weiShuContentDetailModel.getLatitude()+"");

                LangPublishdbModel model = new LangPublishdbModel();
                model.setData(imap.toString());
                if (dragImages != null && dragImages.size() > 0){
                    model.setImgdata(CommonUtils.listToString(dragImages));
                }else {
                    model.setImgdata("");
                }
                model.setUserid(CustomApplication.loginModel.getUid());
                model.setDatatype(0);
                LangPublishService.saveOrUpdate(model);

                /*
                Intent intent = new Intent();
                intent.putExtra("isBacken", true);
                setResult(RESULT_OK, intent);
                finish();
                */

                Intent intent = new Intent(BroadcastDefine.WZTContentPublishing_Notify_Action);
                //发送广播
                sendBroadcast(intent);

                //发送通知
                Intent mIntent = new Intent(BroadcastDefine.WZTContentStartPublish_Notify_Action);
                //发送广播
                sendBroadcast(mIntent);

                if (originImages == null){
                    originImages = new ArrayList<String>();
                }else {
                    originImages.clear();
                }
                if (dragImages == null){
                    dragImages = new ArrayList<String>();
                }else {
                    dragImages.clear();
                }
                mContext = getApplicationContext();
                if (PermissionUtils.hasSDCard() == true){
                    InitCacheFileUtils.initImgDir(FILE_DIR_NAME, FILE_IMG_NAME);//清除图片缓存
                }
                //添加按钮图片资源
                String plusPath = getString(R.string.glide_plus_icon_string) + AppUtils.getPackageInfo(mContext).packageName + "/mipmap/" + R.mipmap.bg_add_imgshow;
                originImages.add(plusPath);//添加按键，超过9张时在adapter中隐藏
                dragImages.addAll(originImages);
                new Thread(new MyRunnable(dragImages, originImages, dragImages, myHandler, false)).start();//开启线程，在新线程中去压缩图片

                et_content.setText("");
                isPublishing = false;
                ToastUtil.show(WZTContentPublishActivity.this, "内容已提交，你可以继续发布新内容");

                return;
            }
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put("token", CustomApplication.loginModel.getToken());
            map.put("title", weiShuContentDetailModel.getTitle());
            map.put("weishuId",weiShuContentDetailModel.getWeishuId()+"");
            String url = "weishu/content/check.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){

                        final JsonMap<String, String> imap = new JsonMap<String, String>();
                        imap.put("title",weiShuContentDetailModel.getTitle());
                        imap.put("weishuId",weiShuContentDetailModel.getWeishuId()+"");
                        imap.put("original",weiShuContentDetailModel.getOriginal()+"");

                        imap.put(APIKey.nationKey,CommonUtils.formatString(weiShuContentDetailModel.getNation()));
                        imap.put(APIKey.provinceKey,CommonUtils.formatString(weiShuContentDetailModel.getProvince()));
                        imap.put(APIKey.cityKey,CommonUtils.formatString(weiShuContentDetailModel.getCity()));
                        imap.put(APIKey.areaKey,CommonUtils.formatString(weiShuContentDetailModel.getArea()));
                        imap.put(APIKey.locationKey,CommonUtils.formatString(weiShuContentDetailModel.getLocation()));
                        imap.put(APIKey.longtitudeKey,weiShuContentDetailModel.getLongtitude()+"");
                        imap.put(APIKey.latitudeKey,weiShuContentDetailModel.getLatitude()+"");

                        LangPublishdbModel model = new LangPublishdbModel();
                        model.setData(imap.toString());
                        if (dragImages != null && dragImages.size() > 0){
                            model.setImgdata(CommonUtils.listToString(dragImages));
                        }else {
                            model.setImgdata("");
                        }
                        model.setUserid(CustomApplication.loginModel.getUid());
                        model.setDatatype(0);
                        LangPublishService.saveOrUpdate(model);

                        /*
                        Intent intent = new Intent();
                        intent.putExtra("isBacken", true);
                        setResult(RESULT_OK, intent);
                        finish();
                        */

                        Intent intent = new Intent(BroadcastDefine.WZTContentPublishing_Notify_Action);
                        //发送广播
                        sendBroadcast(intent);

                        //发送通知
                        Intent mIntent = new Intent(BroadcastDefine.WZTContentStartPublish_Notify_Action);
                        //发送广播
                        sendBroadcast(mIntent);

                        if (originImages == null){
                            originImages = new ArrayList<String>();
                        }else {
                            originImages.clear();
                        }
                        if (dragImages == null){
                            dragImages = new ArrayList<String>();
                        }else {
                            dragImages.clear();
                        }
                        mContext = getApplicationContext();
                        if (PermissionUtils.hasSDCard() == true){
                            InitCacheFileUtils.initImgDir(FILE_DIR_NAME, FILE_IMG_NAME);//清除图片缓存
                        }
                        //添加按钮图片资源
                        String plusPath = getString(R.string.glide_plus_icon_string) + AppUtils.getPackageInfo(mContext).packageName + "/mipmap/" + R.mipmap.bg_add_imgshow;
                        originImages.add(plusPath);//添加按键，超过9张时在adapter中隐藏
                        dragImages.addAll(originImages);
                        new Thread(new MyRunnable(dragImages, originImages, dragImages, myHandler, false)).start();//开启线程，在新线程中去压缩图片

                        et_content.setText("");
                        isPublishing = false;
                        ToastUtil.show(WZTContentPublishActivity.this, "内容已提交，你可以继续发布新内容");

                    }else {
                        CustomApplication.showTip(commonModel, WZTContentPublishActivity.this);
                        isPublishing = false;
                    }
                }

                @Override
                public void onError(String msg) {
                    isPublishing = false;
                }
            });
        }
    }

    //上传内容
    private void uploadLang(){

        weiShuContentDetailModel.setImg(imgString);
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("token", CustomApplication.loginModel.getToken());
        String url = "weishu/content/publish.do";
        if (isRepublish == true){
            url = "weishu/content/edit.do";
            map.put("langid", weiShuContentDetailModel.getLangid());
        }
        map.put("title",weiShuContentDetailModel.getTitle());
        map.put("weishuId",weiShuContentDetailModel.getWeishuId()+"");
        map.put("original",weiShuContentDetailModel.getOriginal()+"");
        map.put("img",CommonUtils.formatString(weiShuContentDetailModel.getImg()));

        map.put(APIKey.nationKey,CommonUtils.formatString(weiShuContentDetailModel.getNation()));
        map.put(APIKey.provinceKey,CommonUtils.formatString(weiShuContentDetailModel.getProvince()));
        map.put(APIKey.cityKey,CommonUtils.formatString(weiShuContentDetailModel.getCity()));
        map.put(APIKey.areaKey,CommonUtils.formatString(weiShuContentDetailModel.getArea()));
        map.put(APIKey.locationKey,CommonUtils.formatString(weiShuContentDetailModel.getLocation()));
        map.put(APIKey.longtitudeKey,weiShuContentDetailModel.getLongtitude()+"");
        map.put(APIKey.latitudeKey,weiShuContentDetailModel.getLatitude()+"");

        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            deleteTempFile();
                            avi.hide();
                            ToastUtil.show(WZTContentPublishActivity.this, "发布成功");
                            setResult(RESULT_OK);
                            finish();
                        }else {
                            avi.hide();
                            isPublishing = false;
                            CustomApplication.showTip(commonModel, WZTContentPublishActivity.this);
                        }
                    }
                });

            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.hide();
                        isPublishing = false;
                        ToastUtil.show(WZTContentPublishActivity.this,"发布失败，请稍后重试");
                    }
                });
            }
        });

    }

    //删除临时文件
    private void deleteTempFile(){
        /*
        if (dragImages != null && dragImages.size() > 0){//删除发布过程中生成的图片
            imgIndex = 0;
            for (;imgIndex < dragImages.size(); imgIndex++){
                if (dragImages.get(imgIndex).contains("http")==false){
                    Bitmap bitmap = ImageUtils.getBitmap(dragImages.get(imgIndex));
                    if (bitmap != null){
                        if (CommonUtils.deleteFileByPath(dragImages.get(imgIndex))==true){
                            Log.e("TAG","发布完成文件删除成功:"+dragImages.get(imgIndex));
                        }
                    }
                }
            }
        }
        */
    }

    //获取上传图片凭证
    private void getUploadInfo(){
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getQiniuTokenDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    qiniuModel = GsonTools.getQiniuModel(data);
                    if (qiniuModel != null){
                        imgIndex = 0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //接着开定时器上传图片
                                startTimer();
                            }
                        });

                    }
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            avi.hide();
                            isPublishing = false;
                            CustomApplication.showTip(commonModel,WZTContentPublishActivity.this);
                        }
                    });

                }
            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.hide();
                        isPublishing = false;
                        ToastUtil.show(WZTContentPublishActivity.this,"发布失败");
                    }
                });
            }
        });
    }

    //上传图片
    private void uploadImg(Bitmap bitmap, final int index){
        final String name = System.currentTimeMillis()+CustomApplication.loginModel.getUid()+".jpg";
        CommonUtils.uploadBytesToQiniu(qiniuModel.getUploadtoken(), qiniuModel.getUploadurl(), name, CommonUtils.bitmapToBytes(bitmap), new QiniuCallBack() {
            @Override
            public void onSuccess(String data) {
                if (CommonUtils.isEmpty(data)){
                    uploadError("发布失败，把图片删除再试试~");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            stopTimer();
                            avi.hide();
                            isPublishing = false;
                            isUploading = false;
                            ToastUtil.show(WZTContentPublishActivity.this,"发布失败，请稍后重新发布~");
                        }
                    });

                }else {
                    if (imgString.length() >0){
                        imgString += ",";
                    }
                    imgString += data;
                    isUploading = false;
                }
            }

            @Override
            public void onModelSuccess(QiniuUploadModel data) {

            }

            @Override
            public void onError(String msg) {
                uploadError("上传图片错误信息："+CommonUtils.formatString(msg));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        stopTimer();
                        avi.hide();
                        isPublishing = false;
                        isUploading = false;
                        ToastUtil.show(WZTContentPublishActivity.this,"发布失败，请稍后再试试~");
                    }
                });
            }
        });
    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    sendMessage(1);
                }
            };
        }
        if(mTimer != null && mTimerTask != null ){
            mTimer.schedule(mTimerTask, delay, period);
            timerFlag = true;
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
            timerFlag = false;
        }
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    //点击图片处理
    private void onClickImageView(View view, int position){
        Log.e("TAG","当前位置："+position);

        if (dragImages == null || dragImages.size() < 2){
            return;
        }

        if (CustomApplication.isWatchingImg == true){
            return;
        }
        CustomApplication.isWatchingImg = true;
        Intent intent = new Intent(WZTContentPublishActivity.this, SelfImagePreviewActivity.class);
        intent.putExtra("number",4);
        intent.putExtra("position",position);
        intent.putExtra("isListImg",true);
        String imgs = "";
        for (int i = 0; i < dragImages.size()-1; i++){
            if(i > 0){
                imgs+=",";
            }
            /*
            if (CommonUtils.fileIsExists(dragImages.get(i))){
                Log.e("TAG","存在图片："+imgs);
            }else {
                Log.e("TAG","不存在图片："+imgs);
            }
            */
            imgs+=dragImages.get(i);
            intent.putExtra("imgs",imgs);
        }


        //View代表方法传入的控件
        int[] viewLocation = new int[2];
        view.getLocationInWindow(viewLocation);
        int viewX = viewLocation[0]; // x 坐标
        int viewY = viewLocation[1];//-(int) (20*ScreenUtils.getScreenDensity(CustomApplication.mContext)); // y 坐标，这里当顶部有状态栏时，要减去状态栏的高度
        intent.putExtra("viewX",viewX);
        intent.putExtra("viewY",viewY);
        intent.putExtra("imgW",imgW);
        intent.putExtra("imgH",imgW);
        startActivity(intent);
        overridePendingTransition(0,0);//可以通过参数设置关闭与要显示的动画效果,0表示无效果.

    }

    //上传错误
    public static void uploadError(String msg){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("msg", msg);
        if (CustomApplication.loginModel != null) {
            map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        String url = "miniapp/langappid/geterror.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("上传错误",data+"\n");
            }

            @Override
            public void onError(String msg) {
                Log.e("上传错误信息",msg+"\n");
            }
        });

    }


}
